<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@page trimDirectiveWhitespaces="true"%>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page language="java" import="java.lang.*" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.util.List" %>
<%@ page import = "java.util.ArrayList"%>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.io.*" %>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>

<%

	//get session
		String strUser = String.valueOf(session.getAttribute("sUser"));
		HttpSession htp_session = request.getSession();
		
	//check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
			<script>alert("This user dont have PERMISSION to access this zone.");</script>
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	
	<%}

	System.out.println("in SAVE :");////////////////try////////////////
	//get value from tag
	String name =  request.getParameter("name");
	String surname = request.getParameter("surname").replaceAll("\\s+","");	
	String username = request.getParameter("username");
	String password = request.getParameter("password");
	String status = request.getParameter("status");
	String workgroup = request.getParameter("workgroup");
	String startDate = request.getParameter("startDate");
	String endDate = request.getParameter("endDate");
	String Salt = request.getParameter("salt");		
	int numRole = Integer.parseInt(request.getParameter("numRole"));
	String[] role = new String[numRole];
	
	for(int i=0; i<numRole; i++) {
		role[i] = request.getParameter("role"+(i+1));
		
		System.out.println("role "+i+" : " + role[i]);////////////////try////////////////
	}
	
	System.out.println("name :" + name);////////////////try////////////////
	System.out.println("surname :" + surname);////////////////try////////////////
	System.out.println("username :" + username);////////////////try////////////////
	System.out.println("password :" + password);////////////////try////////////////
	System.out.println("status :" + status);////////////////try////////////////
	System.out.println("workgroup :" + workgroup);////////////////try////////////////
	System.out.println("startDate :" + startDate);////////////////try////////////////
	System.out.println("endDate :" + endDate);////////////////try////////////////
	System.out.println("numRole :" + numRole);////////////////try////////////////
	
	//set Database Connection
	String hostProps = "";
	String usernameProps  = "";
	String passwordProps  = "";
	String databaseProps = "";
	
	try {
		//get current path
		ServletContext servletContext = request.getSession().getServletContext();
		
		InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
		Properties props = new Properties();
		
		props.load(input);

		hostProps  = props.getProperty("host");
		usernameProps  = props.getProperty("username");
		passwordProps  = props.getProperty("password");
		databaseProps = props.getProperty("database");
	} catch (Exception e) { 
		out.println(e);  
	}
	
	// connect database
	Connection connect = null;		
	try {
		Class.forName("com.mysql.jdbc.Driver");
	
		connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
				"?user=" + usernameProps  + "&password=" + passwordProps+ "&characterEncoding=tis620");
		
		if(connect != null){
			System.out.println("Database Connect Sucesses.");
		} else {
			System.out.println("Database Connect Failed.");	
		}

	} catch (Exception e) {
		out.println(e.getMessage());
		e.printStackTrace();
	}
	
	
	// find index in database
	String index = null;
	
	try {				
		String sql_index = "SELECT *" +
				" FROM full_name"+
				" WHERE name_th='"+name+"' AND surname_th='"+surname+"'";
		
		System.out.println(sql_index);/////try///
		
		ResultSet rs = connect.createStatement().executeQuery(sql_index);	
			
					
		while(rs.next()) {			
			index = rs.getString("index");
		}
		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	
	System.out.println("index :"+index);////////////try/////////////////////	
	// IF dont have that name
	if(null ==index){
		out.print("Noname");
	}else{	
		// insert data to database
		String passwordSalt = password + Salt;
		String password_encrypt = PasswordHandler.encryptPassword(passwordSalt);
				
		String test = PasswordHandler.encryptPassword(password);
		System.out.println("password_encrypt: "+password_encrypt);/////////////////////try///////////////////////////////
		System.out.println("test: "+test);/////////////////////try///////////////////////////////		
		
		String sql_account = "INSERT INTO  `account`(`index`, `username`, `start_date`, `end_date`)"
							+ " VALUES ('"+ index +"', '"+ username +"', '"+ startDate +"', "+ endDate + ")";
				
		String sql_user = "INSERT INTO `user`(`username`, `password`, `status`, `workgroup_id`, `remove`,`salt`)"
							+ " VALUES ('" + username + "', '" + password_encrypt +"', " + status + ", " + workgroup +", false,"+ Salt + ")"; 
				
		System.out.println(sql_account);/////////////////////try///////////////////////////////
		System.out.println(sql_user);/////////////////////try///////////////////////////////
		
		
		try {		
				// insert data into account 
				connect.createStatement().executeUpdate(sql_account);
				
				/* Log file */			
				String log_account = "admin add account";
				Log.writeAdminFile(log_account);
				Log.writeAdminFile(sql_account);
				
				// insert data into user
				connect.createStatement().executeUpdate(sql_user);
				
				/* Log file */	
				String log_user = "admin add user";
				Log.writeAdminFile(log_user);
				Log.writeAdminFile(sql_user);
				
				String log_autho = "admin add authorization ";
				Log.writeAdminFile(log_autho);
	
				// insert data into authorization
				for(int i=0 ;i<numRole; i++) {
					String sql_autho = "INSERT INTO `authorization`(`role_id`, `username`) VALUES (" + role[i] + ", '" + username + "')";
					
					System.out.println(sql_autho);/////////////////////try///////////////////////////////
					
					connect.createStatement().executeUpdate(sql_autho);
						
					/* Log file */	
					Log.writeAdminFile(sql_autho);
					
				}
							
				out.print("Success");
		} catch (SQLException e) {
			e.printStackTrace();
			out.print("Failed");
		}		
		
		connect.close();
	
	}
		
%>